var prefix = ctx + "implement";
function submitApply(isSave) {
    //提交之前校验参数
    if (checkProposerParam()&&checkEvidenceParam()){
        //var data = $('#formId').serialize();
        //被执行人数据
        var boData=[];
        $("#bo_hidden").children().each(function () {
            var value=$(this).attr("value");
            var boStr="{"+value+"}";
            boData.push(eval('(' + boStr + ')'));
        });
        //证据数据
        var enviceData=[];
        $("#envice_hidden").children().each(function () {
            var value=$(this).attr("value");
            var enviceStr="{"+value+"}";
            enviceData.push(eval('(' + enviceStr + ')'));
        });
        var saveType=null;
        if (isSave){
            saveType=1;
        }
        var overdueDay =$("#overdue_day").val()
        var arbitramentNumber=$("#arbitramentNumber").val()
        var data={
            "caseId":getCaseId(),
            "saveType":saveType,
            //案件分类信息
            "caseTypeVo":{
                "applicantEnterpriseIndustry":$("#caseTypeVo_applicant_enterprise_industry").val(),
                "caseType":$("#caseTypeVo_case_type").val(),
                "enforcementBasis":$("#caseTypeVo_enforcement_basis").val(),
                "loanGetWay":$("#caseTypeVo_loan_get_way").val(),
                "execProvince":$("#caseTypeVo_exec_province").val(),
                "execCity":$("#caseTypeVo_exec_city").val()
            },
            //执行申请人信息
            "applicantUserInfoVo":getApplicantUserInfoVo(),
            //被执行人信息
            "proposerUserInfoVos":boData,
            //证据信息
            "evidenceInfoVo":{
                "biddingAmount":$("#bidding_amount").val(),
                "arbitrationCommissionName":$("#arbitration_commission_name").val(),
                "attachmentEvidenceVos":enviceData
            },
            "arbitramentNumber":arbitramentNumber,
            "overdueDay":overdueDay,
        };
        //组装数据
        //$.operate.saveTab(prefix + "/selfApply", JSON.stringify(data));
        var config = {
            url: prefix + "/applicantSubmit",
            type: "post",
            dataType: "json",
            contentType:'application/json',
            data: JSON.stringify(data),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                if (typeof callback == "function") {
                    callback(result);
                }
                $.operate.successTabCallback(result);
            }
        };
        $.ajax(config)
        //$.operate.post(prefix + "/selfApply", data);
    }
    /*if ($.validate.form()){
        var data = $('#formId').serialize();
        $.operate.saveTab(prefix + "/selfApply", data);
    }*/
}

function getCaseId(){
    var caseId = $("#caseId").val();
    if (null == caseId || '' == caseId || undefined == caseId) {
        return null;
    }
    return caseId;
}

//上传控件
$(document).ready(function () {
    $("#fileinput-only-more").fileinput({
        //详细参数配置请参考  http://doc.ruoyi.vip/ruoyi/document/zjwd.html#jasny-bootstrap
        theme: 'explorer-fas',
        uploadUrl: '/oss/uploadFile',
        overwriteInitial: false,
        initialPreviewAsData: true,
        maxFileCount: 100, //表示允许同时上传的最大文件个数
        enctype: 'multipart/form-data',
        validateInitialCount:true,
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        autoReplace: false, //是否自动替换当前图
        uploadAsync: true, //是否为异步上传
        maxFileSize: 20000, //允许上传的最大文件大小 单位为kb
        //默认显示的图片预览
        initialPreview: [
            //"/img/profile.jpg"
        ]
    });
    //上传成功之后的处理
    $("#fileinput-only-more").on("fileuploaded", function(event, data, proviewId, index) {
        var url = data.response.fileUrl;
        var name=data.response.fileName;
        var size=data.response.fileSize;
        //表格插入行
        $("#bootstrap-table-evi").bootstrapTable('insertRow', {
            index: 0, // 你想插入到哪，0表示第一行
            row: getData(url,name,size)
        });
    });
    //清空预览图片的响应事件
    $("#fileinput-only-more").on("filecleared",function(event, data, msg){
        //清除隐藏域的值
       /* $("#attachmentUrl").val("");
        $("#attachmentName").val("");
        $("#attachmentSize").val("");*/
    });

    var caseId = $("#caseId").val();
    //初始化表格
    //初始化证据表格
    initTable(caseId);
    //初始化被申请人表格
    initBoTable(caseId);
    //被申请人表格添加行
    $("#addBorrower").on("click",function () {
        //表单数据校验
        if (!checkProposerUserInfoParam()){
            return false;
        }
        //表格插入行
        $("#bootstrap-table-bo").bootstrapTable('insertRow', {
            index: 0, // 你想插入到哪，0表示第一行
            row: getBoData()
        })
        //清空表单数据
        $("#proposer_name").val("");
        $("#proposer_id_card_no").val("");
        $("#proposer_work_unit").val("");
        $("#proposer_mobile").val("");
        $("#proposer_email").val("");
        $("#proposer_country").val("");
        $("#proposer_nation").val("");
        $("#proposer_address").val("");
        $("#proposer_gender").val("");
        $("#l_proposer_name").val("");
        $("#l_proposer_id_card_no").val("");
        $("#l_proposer_legal_person_name").val("");
        $("#l_proposer_legal_person_card").val("");
        $("#l_proposer_job").val("");
        $("#l_proposer_mobile").val("");
        $("#l_proposer_email").val("");
        $("#l_proposer_country").val("");
        $("#l_proposer_nation").val("");
        $("#l_proposer_address").val("");
    });
});

function getData(attachmentUrl,attachmentName,attachmentSize) {
    //当前表格的数据总数
    var rows=$("#bootstrap-table-evi").bootstrapTable("getData").length;
    var num=rows+1;
    var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        //"num":"0_"+num,
        "fileSize": attachmentSize,
        "fileUrl": attachmentUrl,
        "fileName": attachmentName
    };
    //隐藏域添加值，最后提交的时候用
    var value="fileSize:"+attachmentSize+",fileName:\""+
        attachmentName+"\",fileUrl:\""+attachmentUrl+"\"";
    $("#envice_hidden").append("<input type='hidden' name='"+attachmentName+"' value='"+value+"'/>");
    return temp;
}

function initTable(caseId) {
    var options = {
        id:"bootstrap-table-evi",
        //data:data,
        url: prefix + "/initEviTableData",
        queryParams:{
            "caseId":caseId
        },
        showSearch: false,
        showRefresh: false,
        showToggle: false,
        showColumns: false,
        pagination: false,//是否分页
        columns: [{
            checkbox: false
        },{
                field: 'fileName',
                title: '附件名称'
            },
            {
                field: 'fileSize',
                title: '附件大小'
            },
            {
                title: '操作',
                align: 'center',
                formatter: function(value, row, index) {
                    var actions = [];
                    var tableName="bootstrap-table-evi";
                    actions.push('<button class="btn btn-success btn-xs fileView" data-id="'+row.id+'" data-name="'+row.fileName+'" data-url="'+row.fileUrl+'" onclick="showEnviceRow(' + row.id + ',\'' + row.fileName + '\',\'' + row.fileUrl + '\')">查看</button>');
                    actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeEnviceRow(\'' + row.fileName + '\',\'' + tableName + '\')"><i class="fa fa-remove"></i>删除</a> ');
                    return actions.join('');
                }
            }]
    };
    $.table.init(options);
}

//查看附件
function showEnviceRow(id,fileName,fileUrl) {
    if ($.common.isNotEmpty(id)){
        $.modal.openTab("查看附件", "/attachment/preview/"+id);
    }else {
        $.modal.openTab("查看附件", "/attachment/showFile?fileName="+fileName+"&&fileUrl="+fileUrl);
    }
}

function removeEnviceRow(num,tableName) {
    var nums=[];
    nums.push(num);
    $("#"+tableName).bootstrapTable('remove', {
        field: 'fileName',
        values: nums
    })
    //删除相关隐藏域的信息
    $("#envice_hidden").children().each(function () {
        var name=$(this).attr("name");
        var number=name.split("_")[1];
        if (name==num){
            $(this).remove();
        }
    })
}

function initBoTable(caseId){
    var options = {
        id:"bootstrap-table-bo",
        //data:data,
        url: prefix + "/initBoTableData",
        queryParams:{
            "caseId":caseId
        },
        showSearch: false,
        showRefresh: false,
        showToggle: false,
        showColumns: false,
        pagination: false,//是否分页
        columns: [{
            checkbox: false
        },{
            field: 'proposerTypeDes',
            title: '被执行人类型'
        },
            {
                field: 'proposerName',
                title: '名称'
            },
            {
                field: 'proposerIdCardNo',
                title: '证件号'
            },
            {
                field: 'proposerWorkUnit',
                title: '工作单位'
            },
            {
                field: 'proposerMobile',
                title: '手机号'
            },
            {
                field: 'proposerEmail',
                title: '邮箱'
            },
            {
                field: 'proposerCountry',
                title: '国籍'
            },
            {
                field: 'proposerNation',
                title: '民族'
            },
            {
                field: 'proposerAddress',
                title: '地址'
            },
            {
                field: 'proposerGenderDes',
                title: '性别'
            },
            {
                field: 'proposerLegalPersonName',
                title: '法人姓名'
            },
            {
                field: 'proposerLegalPersonCard',
                title: '法人证件号'
            },
            {
                field: 'proposerJob',
                title: '职务'
            },
            {
                title: '操作',
                align: 'center',
                formatter: function(value, row, index) {
                    var actions = [];
                    var tableName="bootstrap-table-bo";
                    actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="removeBoRow(\'' + row.proposerName + '\',\'' + tableName + '\')"><i class="fa fa-remove"></i>删除</a> ');
                    return actions.join('');
                }
            }]
    };
    $.table.init(options);
}

function removeBoRow(num,tableName) {
    var nums=[];
    nums.push(num);
    $("#"+tableName).bootstrapTable('remove', {
        field: 'proposerName',
        values: nums
    })
    //删除相关隐藏域的信息
    $("#bo_hidden").children().each(function () {
        var name=$(this).attr("name");
        var value=$(this).attr("value");
        var number=name.split("_")[1];
        if (num==name){
            $(this).remove();
        }
    })
}

function getBoData() {
    //获取表单中的值
    var partyType=$("input[name='proposer_type']:checked").val();
    var partyTypeDes="自然人";
    if (partyType==2){
        partyTypeDes="法人";
    }
    var proposer_name,proposer_id_card_no,proposer_work_unit,proposer_mobile,proposer_email, proposer_country,proposer_nation,
        proposer_address,proposer_gender,proposer_legal_person_name,proposer_legal_person_card,proposer_job,sexDes;
    if (partyType==1){
        //自然人
        proposer_name=$("#proposer_name").val();
        proposer_id_card_no=$("#proposer_id_card_no").val();
        proposer_work_unit=$("#proposer_work_unit").val();
        proposer_mobile=$("#proposer_mobile").val();
        proposer_email=$("#proposer_email").val();
        proposer_country=$("#proposer_country").val();
        proposer_nation=$("#proposer_nation").val();
        proposer_address=$("#proposer_address").val();
        proposer_gender=$("#hidden_proposer_gender").val();
        sexDes=$("#proposer_gender").text();
        proposer_legal_person_name="";
        proposer_legal_person_card="";
        proposer_job="";
    }else if (partyType==2){
        //法人
        proposer_name=$("#l_proposer_name").val();
        proposer_id_card_no=$("#l_proposer_id_card_no").val();
        proposer_legal_person_name=$("#l_proposer_legal_person_name").val();
        proposer_legal_person_card=$("#l_proposer_legal_person_card").val();
        proposer_job=$("#l_proposer_job").val();
        proposer_mobile=$("#l_proposer_mobile").val();
        proposer_email=$("#l_proposer_email").val();
        proposer_country=$("#l_proposer_country").val();
        proposer_nation=$("#l_proposer_nation").val();
        proposer_address=$("#l_proposer_address").val();
        proposer_work_unit="";
        proposer_gender=null;
        sexDes="";
    }else {
        $.modal.alertWarning('类型不正确');
    }
    //当前表格的数据总数
    var rows=$("#bootstrap-table-bo").bootstrapTable("getData").length;
    var num=rows+1;
    var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        //"num":"0_"+num,
        "proposerTypeDes": partyTypeDes,
        "proposerName": proposer_name,
        "proposerIdCardNo": proposer_id_card_no,
        "proposerWorkUnit": proposer_work_unit,
        "proposerMobile": proposer_mobile,
        "proposerEmail": proposer_email,
        "proposerCountry": proposer_country,
        "proposerNation": proposer_nation,
        "proposerAddress": proposer_address,
        "proposerGenderDes": sexDes,
        "proposerLegalPersonName": proposer_legal_person_name,
        "proposerLegalPersonCard": proposer_legal_person_card,
        "proposerJob": proposer_job
    };
    //隐藏域添加值，最后提交的时候用
    var value="proposerType:"+partyType+",proposerName:\""+proposer_name+"\",proposerIdCardNo:\""+proposer_id_card_no+"\",proposerWorkUnit:\""+proposer_work_unit +"\",proposerMobile:\""+proposer_mobile
        +"\",proposerEmail:\""+ proposer_email+"\",proposerCountry:\""+proposer_country+"\",proposerNation:\""+proposer_nation+"\",proposerAddress:\""+proposer_address
        +"\",proposerGender:"+proposer_gender+",proposerLegalPersonName:\""+proposer_legal_person_name+"\",proposerLegalPersonCard:\""+proposer_legal_person_card +"\",proposerJob:\""+proposer_job+"\"";
    $("#bo_hidden").append("<input type='hidden' name='"+proposer_name+"' value='"+value+"'/>");
    return temp;
}

/**
 * 组装执行申请人信息
 *
 * @param null
 * @author Qiu Rui
 * @date 2020/11/10 5:07 下午
 * @return
 */
function getApplicantUserInfoVo() {
    var applicantType=$("#hidden_applyImplementVo_applicant_type").val();
    var applicantName,applicantGender,applicantIdCardNo,applicantMobile,applicantEmail,applicantAddress,
        applicantCountry,applicantNation,applicantWorkUnit,applicantLegalPersonName,applicantLegalPersonCard;
    if (applicantType==1){
        //自然人
        applicantName=$("#applyImplementVo_applicant_name").val();
        applicantGender=$("#hidden_applyImplementVo_applicant_gender").val();
        applicantIdCardNo=$("#applyImplementVo_applicant_id_card_no").val();
        applicantMobile=$("#applyImplementVo_applicant_mobile").val();
        applicantEmail=$("#applyImplementVo_applicant_email").val();
        applicantAddress=$("#applyImplementVo_applicant_address").val();
        applicantCountry=$("#applyImplementVo_applicant_country").val();
        applicantNation=$("#applyImplementVo_applicant_nation").val();
        applicantWorkUnit=$("#applyImplementVo_applicant_work_unit").val();
        applicantLegalPersonName=null;
        applicantLegalPersonCard=null;
    }else if (applicantType==2){
        //法人
        applicantName=$("#b_applyImplementVo_applicant_user_name").val();
        applicantIdCardNo=$("#b_applyImplementVo_applicant_id_card_no").val();
        applicantLegalPersonName=$("#b_applyImplementVo_applicant_legal_person_name").val();
        //applicantLegalPersonCard=$("#b_applyImplementVo_applicant_legal_person_card").val();
        applicantLegalPersonCard=null;
        applicantMobile=$("#b_applyImplementVo_applicant_mobile").val();
        applicantEmail=$("#b_applyImplementVo_applicant_email").val();
        applicantAddress=$("#b_applyImplementVo_applicant_address").val();
        //applicantCountry=$("#b_applyImplementVo_applicant_country").val();
        applicantCountry=null;
        //applicantNation=$("#b_applyImplementVo_applicant_nation").val();
        applicantNation=null;
        applicantWorkUnit=null;
        applicantGender=null;
    }
    var applicantUserInfoVo={
        "applicantType":applicantType,
        "applicantName":applicantName,
        "applicantGender":applicantGender,
        "applicantIdCardNo":applicantIdCardNo,
        "applicantMobile":applicantMobile,
        "applicantCountry":applicantCountry,
        "applicantNation":applicantNation,
        "applicantLegalPersonName":applicantLegalPersonName,
        "applicantLegalPersonCard":applicantLegalPersonCard,
        "applicantEmail":applicantEmail,
        "applicantAddress":applicantAddress,
        "applicantWorkUnit":applicantWorkUnit
    };
    return applicantUserInfoVo;
}

/**
 * 加载执行申请人信息
 *
 * @param null 
 * @author Qiu Rui
 * @date 2020/11/10 10:27 上午 
 * @return 
 */
function initApplicationUserData() {
    $.ajax({
        url: prefix + "/initApplicationUserData",
        type: "post",
        dataType: "json",
        contentType:'application/json',
        success: function(result) {
            if (result.code == web_status.SUCCESS) {
                //判断用户类型，显示相应的数据
                var applicantType=result.data.applicantType;
                $("#hidden_applyImplementVo_applicant_type").val(applicantType);
                //自然人
                if (applicantType==1){
                    $("#applyImplementVo_naturalPerson").show();
                    $("#b_applyImplementVo_legalPerson").hide();

                    $("#applyImplementVo_applicant_name").val(result.data.applicantName);
                    $("#applyImplementVo_applicant_id_card_no").val(result.data.applicantIdCardNo);
                    $("#applyImplementVo_applicant_mobile").val(result.data.applicantMobile);
                    $("#applyImplementVo_applicant_email").val(result.data.applicantEmail);
                    $("#applyImplementVo_applicant_address").val(result.data.applicantAddress);
                    $("#hidden_applyImplementVo_applicant_gender").val(result.data.applicantGender);
                    $("#applyImplementVo_applicant_gender").text(result.data.applicantGenderDes);
                    //$("#applyImplementVo_applicant_country").text(result.data.applicantCountry);
                   // $("#applyImplementVo_applicant_nation").text(result.data.applicantNation);
                }else if (applicantType==2){
                    //法人
                    $("#applyImplementVo_naturalPerson").hide();
                    $("#b_applyImplementVo_legalPerson").show();

                    $("#b_applyImplementVo_applicant_user_name").val(result.data.applicantName);
                    $("#b_applyImplementVo_applicant_id_card_no").val(result.data.applicantIdCardNo);
                    $("#b_applyImplementVo_applicant_legal_person_name").val(result.data.applicantLegalPersonName);
                   // $("#b_applyImplementVo_applicant_legal_person_card").val(result.data.applicantLegalPersonCard);
                    $("#b_applyImplementVo_applicant_mobile").val(result.data.applicantMobile);
                    $("#b_applyImplementVo_applicant_email").val(result.data.applicantEmail);
                    $("#b_applyImplementVo_applicant_address").val(result.data.applicantAddress);
                    //$("#b_applyImplementVo_applicant_country").text(result.data.applicantCountry);
                    //$("#b_applyImplementVo_applicant_nation").text(result.data.applicantNation);
                }
            }
        }
    });
}

/**
 * 身份证号解析性别
 *
 * @param pre
 * @author Qiu Rui
 * @date 2020/11/10 3:10 下午
 * @return
 */
function onblurIdCardNo(pre) {
    var id_card_no=$("#"+pre+"_id_card_no").val();
    if (null == id_card_no || '' == id_card_no || undefined == id_card_no) {
        return false;
    }
    //截取身份证倒数第二位
    var last = id_card_no[id_card_no.length - 2];
    var sex;
    var sexDes;
    if(last % 2 != 0){
        sex=1;
        sexDes="男";
    }else{
        sex=2;
        sexDes="女";
    }
    $("#"+pre+"_gender").text(sexDes);
    $("#hidden_"+pre+"_gender").val(sex);
}


